package io.renren.modules.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import eu.bitwalker.useragentutils.UserAgent;
import io.renren.common.utils.HttpContextUtils;
import io.renren.common.utils.IPUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.sys.dao.SysLoginInforDao;
import io.renren.modules.sys.entity.SysLoginInforEntity;
import io.renren.modules.sys.service.SysLoginInforService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;


@Service("popSysLoginInforService")
public class SysLoginInforServiceImpl extends ServiceImpl<SysLoginInforDao, SysLoginInforEntity> implements SysLoginInforService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<SysLoginInforEntity> page = this.selectPage(
                new Query<SysLoginInforEntity>(params).getPage(),
                new EntityWrapper<SysLoginInforEntity>()
        );

        return new PageUtils(page);
    }

    // 保存登录信息
    @Override
    //@Async
    public void saveLoginInfo(String userName, String status, String msg) {
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        final UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        final String ip = IPUtils.getIpAddr(request);

        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();

        SysLoginInforEntity popSysLoginInfor = new SysLoginInforEntity();
        popSysLoginInfor.setLoginName(userName);
        popSysLoginInfor.setSellerId(1L);
        popSysLoginInfor.setIpaddr(ip);
        //popSysLoginInfor.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        popSysLoginInfor.setBrowser(browser);
        popSysLoginInfor.setOs(os);
        popSysLoginInfor.setMsg(msg);
        popSysLoginInfor.setStatus(status);
        popSysLoginInfor.setLoginTime(new Date());

        this.insert(popSysLoginInfor);

    }

}
